package com.jzr.mybatis.generator;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class GeneratorHelper {
    public static void generate(MyConfig myConfig){
        if(myConfig.tableNames == null || myConfig.tableNames.trim().length()<=0){
            return;
        }
        String dbUrl = myConfig.dbUrl;
        String dbDriverName = myConfig.dbDriverName;
        String dbUsername = myConfig.dbUsername;
        String dbPassword = myConfig.dbPassword;
        String subProjectPath = myConfig.subProjectPath;
        String packagePath = myConfig.packagePath;
        String modelName = myConfig.modelName;
        String tableNames = myConfig.tableNames;
        boolean enableMapper = myConfig.enableMapper;
        boolean enableService = myConfig.enableService;
        boolean enableController = myConfig.enableController;
        boolean enableOther = myConfig.enableOther;
        boolean fileOverride = myConfig.fileOverride;
        int enableGetId = myConfig.enableGetId;  //0:不生成getId, 1:生成getId
        int isSuperEntityGeneric = myConfig.isSuperEntityGeneric; //id字段数据类型
        String superEntityClass = myConfig.superEntityClass;

        // 代码生成器
        AutoGenerator mpg = new AutoGenerator();

        // 全局配置
        MyGlobalConfig gc = new MyGlobalConfig();
        String projectPath = System.getProperty("user.dir");
        gc.setOutputDir(projectPath + "/" + subProjectPath + "/src/main/java");
        gc.setAuthor("henry");
        gc.setOpen(false);
        gc.setSwagger2(true); //实体属性 Swagger2 注解
        //gc.setEntityName("TStudent");
        //gc.setActiveRecord(true);
        gc.setEnableCache(false);// XML 二级缓存
        gc.setIdType(IdType.AUTO);
        gc.setFileOverride(fileOverride);
        gc.setBaseColumnList(false);
        gc.setBaseResultMap(false);
        gc.setMapperName("%sMapper");
        gc.setXmlName("%sMapper");
        gc.setServiceName("%sService");
        gc.setServiceImplName("%sServiceImpl");
        gc.setControllerName("%sController");
        gc.setDateType(DateType.TIME_PACK); //java8 LocalDate
        gc.setEnableController(enableController);
        gc.setEnableService(enableService);
        gc.setEnableMapper(enableMapper);
        gc.setEnableOther(enableOther);
        mpg.setGlobalConfig(gc);

        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl(dbUrl);
        // dsc.setSchemaName("public");
        dsc.setDriverName(dbDriverName);
        dsc.setUsername(dbUsername);
        dsc.setPassword(dbPassword);
//        dsc.setTypeConvert(
//                // 自定义数据库表字段类型转换【可选】1.8 新增时间对象
//                new MySqlTypeConvert() {
//                    @Override
//                    public IColumnType processTypeConvert(GlobalConfig globalConfig, String fieldType) {
//                        if (fieldType.toLowerCase().equals("bit")) {
//                            return DbColumnType.BOOLEAN;
//                        }
//                        if (fieldType.toLowerCase().equals("tinyint")) {
//                            return DbColumnType.BOOLEAN;
//                        }
//                        if (fieldType.toLowerCase().equals("date")) {
//                            return DbColumnType.LOCAL_DATE;
//                        }
//                        if (fieldType.toLowerCase().equals("time")) {
//                            return DbColumnType.LOCAL_TIME;
//                        }
//                        if (fieldType.toLowerCase().equals("datetime")) {
//                            return DbColumnType.LOCAL_DATE_TIME;
//                        }
//                        return super.processTypeConvert(globalConfig, fieldType);
//                    }
//                }
//        );
        mpg.setDataSource(dsc);

        // 包配置
        PackageConfig pc = new PackageConfig();
        //pc.setModuleName(scanner("模块名"));
        pc.setModuleName(modelName);
        pc.setParent(packagePath);
        pc.setController("controller");
        pc.setService("service");
        pc.setServiceImpl("service.impl");
        pc.setMapper("mapper");
        pc.setEntity("model");
        mpg.setPackageInfo(pc);

        // 自定义配置
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("enableGetId", enableGetId);
                map.put("isSuperEntityGeneric",isSuperEntityGeneric);
                this.setMap(map);
            }
        };

        // 如果模板引擎是 freemarker
        String templatePath = "/templates/mapper2.xml.ftl";
        // 如果模板引擎是 velocity
        //String templatePath = "/templates/mapper.xml.vm";

        // 自定义输出配置
        List<FileOutConfig> focList = new ArrayList<>();
        // 自定义配置会被优先输出
        focList.add(new FileOutConfig(templatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return projectPath + "/" + subProjectPath + "/src/main/resources/mapper/" + pc.getModuleName()
                        + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
            }
        });
        /*
        cfg.setFileCreate(new IFileCreate() {
            @Override
            public boolean isCreate(ConfigBuilder configBuilder, FileType fileType, String filePath) {
                // 判断自定义文件夹是否需要创建
                checkDir("调用默认方法创建的目录");
                return false;
            }
        });
        */
        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);

        // 配置模板
        TemplateConfig templateConfig = new TemplateConfig();

        // 配置自定义输出模板
        //指定自定义模板路径，注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别
        templateConfig.setEntity("templates/entity2.java");
        templateConfig.setMapper("templates/mapper2.java");
        templateConfig.setService("templates/service2.java");
        templateConfig.setServiceImpl("templates/serviceImpl2.java");
        // templateConfig.setController();

        templateConfig.setXml(null);
        mpg.setTemplate(templateConfig);

        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        strategy.setSuperEntityClass(superEntityClass);
        strategy.setEntityLombokModel(true);
        strategy.setRestControllerStyle(true);
        strategy.setEntityBooleanColumnRemoveIsPrefix(true);
        strategy.setEntitySerialVersionUID(true);
        strategy.setEntityTableFieldAnnotationEnable(true);
        //strategy.setTablePrefix("t_");

        //strategy.setSuperControllerClass("com.cenxi.scm.common.BaseController");
        //strategy.setInclude(scanner("表名，多个英文逗号分割").split(","));
        strategy.setInclude(tableNames.split(","));
        //strategy.setSuperEntityColumns("id");
        strategy.setControllerMappingHyphenStyle(false);
        //strategy.setTablePrefix(pc.getModuleName() + "_");
        strategy.setEntityBooleanColumnRemoveIsPrefix(false);

        mpg.setStrategy(strategy);
        mpg.setTemplateEngine(new MyFreemarkerTemplateEngine(gc));
        mpg.execute();
    }
}
